package controller

import (
	"context"
	"ez/apps/core/auto/controller"
	core "ez/apps/core/document"
	"ez/apps/core/service"
	"ez/config/code"
	"ez/config/r"
	"ez/custom/cc"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
)

type LoginAdminController struct {
	controller.UserAutoController
}

func init() {
	c := &LoginAdminController{}
	ez.CreateApi(r.Api("/login"), c.LoginAction)
	ez.CreateApi(r.AdminApi("/password"), c.PasswordAction)
}

// func (c UserController) Get(session *ez.Session) { /* 在这里面重构 */ }
// func (c UserController) List(session *ez.Session) { /* 在这里面重构 */ }

func (c LoginAdminController) LoginAction(session *ez.Session) {
	this := cc.New(session)
	username := this.Get("username").IsString()
	if username == "" {
		this.ReturnError(code.Error, "请输入账号", "")
		return
	}
	password := this.Get("password").IsString()
	if password == "" {
		this.ReturnError(code.Error, "请输入密码", "")
		return
	}
	crud := core.NewUserCrud()
	find, err := crud.FindOneBy(ss.M{"account": username}, nil)
	if err != nil {
		this.ReturnError(code.Error, "账号不存在", "")
		return
	} else {
		if service.GenPass(password, find.Salt) != find.Password {
			//密码错误
			this.ReturnError(code.Error, "密码错误", "")
			return
		} else {
			//登录成功
			if find.Token == "" || (len(find.Token) > 3 && find.Token[:3] != "ABC") {
				find.Token = service.EncodeUserToken(find)
				ez.LogToConsole(find.Token)
				err = find.Save()
				if this.Try(err) {
					return
				}
				//信息存储到redis以便其他系统获取
				service.SetUserToRedis(find)

				data := make(map[string]interface{})
				data["account"] = find
				ez.DispatchToMany(service.EventUserLogin, data, context.TODO())
				this.ReturnSuccess("登录成功", data)
				return
			}
			return
		}
	}
}

func (c LoginAdminController) PasswordAction(session *ez.Session) {
	this := cc.New(session)
	old := this.Get("old").IsString()
	newP := this.Get("new").IsString()
	token := this.GetAuthToken()
	println(service.DecodeUserToken(token))
	userCrud := core.NewUserCrud()
	find, e := userCrud.FindOneBy(ss.M{"token": token}, nil)
	if this.Try(e) {
		return
	}
	if find.Id == 0 {
		this.ReturnError(code.ErrorAuth, "登录超时", "")
		return
	}
	if find.Password != service.GenPass(old, find.Salt) {
		this.ReturnError(code.Error, "密码错误", "")
		return
	}
	find.Password = service.GenPass(newP, find.Salt)
	if this.Try(find.Save()) {
		return
	}
	this.ReturnSuccess("修改成功", "")
}
